/*******************************************************************************
* Copyright (c) 2010, 2018 西安秦晔信息科技有限公司
* Licensed under the Apache License, Version 2.0 (the "License");
*    you may not use this file except in compliance with the License.
*    You may obtain a copy of the License at
*
*       http://www.apache.org/licenses/LICENSE-2.0
*
*    Unless required by applicable law or agreed to in writing, software
*    distributed under the License is distributed on an "AS IS" BASIS,
*    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*    See the License for the specific language governing permissions and
*    limitations under the License.
*******************************************************************************/
package com.qinyeit.serviceapp.service.dishes.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.qinyeit.serviceapp.entity.*;
import com.qinyeit.serviceapp.entity.enums.State;
import com.qinyeit.serviceapp.exception.BusinessRunTimeException;
import com.qinyeit.serviceapp.repository.dishes.ChangePriceRepository;
import com.qinyeit.serviceapp.service.branchs.BranchDataReleasedServiceImpl;
import com.qinyeit.serviceapp.service.dishes.ChangePriceBranchService;
import com.qinyeit.serviceapp.service.dishes.ChangePriceLogService;
import com.qinyeit.serviceapp.service.dishes.ChangePriceService;
import com.qinyeit.serviceapp.service.dishes.DishesService;
import com.qinyeit.serviceapp.service.organization.BranchService;
import com.qinyeit.serviceapp.utils.SearchUtils;
import com.qinyetech.springstage.core.date.DateUtils;
import com.qinyetech.springstage.core.entity.search.Searchable;
import com.qinyetech.springstage.core.lang.QyMap;
import com.qinyetech.springstage.core.repository.jdbc.PageNamedParameterJdbcTemplate;
import com.qinyetech.springstage.core.service.BaseService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Map;

/** 
 * ClassName: ChangePriceServiceImpl <br/> 
 * Function: 菜品变价单 业务实现 <br/> 
 * date: 2018-11-27 15:11:36 <br/> 
 * 
 * @author liuwenjin
 * @version 1.0
 * @since JDK 1.8
 */
@Service
@Transactional
public class ChangePriceServiceImpl extends BaseService<ChangePrice, Long> implements ChangePriceService {


	@Autowired
	private ChangePriceRepository changePriceRepository;
	@Autowired
	private DishesService dishesService;
	@Autowired
	private ChangePriceLogService changePriceLogService;
	@Autowired
	private BranchService branchService;
	@Autowired
	private ChangePriceBranchService changePriceBranchService;
	@Autowired
	private PageNamedParameterJdbcTemplate jdbcTemplate;
	@Autowired
	private BranchDataReleasedServiceImpl branchDataReleasedService;


	//TODO 偏移分钟数 将来设为配置项
	private static int minute = 5;

	@Override
	public void saveData(JSONObject data, Long merchantGroupId, String operator) {
		JSONObject changePriceData = data.getJSONObject("changePrice");
		JSONArray dishesData = data.getJSONArray("dishes");
		JSONArray branchData = data.getJSONArray("branchs");
		if(changePriceData==null){
			throw new BusinessRunTimeException("变价信息为空",10001);
		}
		if(CollectionUtils.isEmpty(dishesData)){
			throw new BusinessRunTimeException("请选择菜品",10002);
		}

		if(CollectionUtils.isEmpty(branchData)){
			throw new BusinessRunTimeException("生效机构不能为空",10003);
		}
		if (changePriceData.getLong("menuId")==null){
			throw new BusinessRunTimeException("请选择菜谱",10004);
		}
		if (StringUtils.isBlank(changePriceData.getString("reason"))){
			throw new BusinessRunTimeException("请填写变价原因",10005);
		}
		if (StringUtils.isBlank(changePriceData.getString("effectiveTime"))){
			throw new BusinessRunTimeException("请选择生效日期",10006);
		}

		Dishes dishes = null;
		JSONObject item ;
		ChangePrice changePrice = null;
		ChangePriceLog log = null;
		ChangePriceBranch changePriceBranch = null;

		List<ChangePrice> changePriceList = Lists.newArrayList();

		for (int i = 0; i < dishesData.size(); i++) {

			item = dishesData.getJSONObject(i);
			dishes = dishesService.findById(item.getLong("dishesId"));
			if(dishes==null){
				throw new BusinessRunTimeException("菜品不存在",10003);
			}
			changePrice = this.getChangePrice(merchantGroupId,changePriceData.getLong("menuId"),item.getLong("dishesId"),item.getLong("specId"));
			if (changePrice==null){
				changePrice = new ChangePrice();
			}
			changePrice.setMerchantGroupId(merchantGroupId);
			changePrice.setDishesId(item.getLong("dishesId"));
			//生效日期如果是今天 则推迟5分钟
			if (DateUtils.today().equals(changePriceData.getString("effectiveTime"))){
				changePrice.setEffectiveTime(DateUtils.offsiteMinute(new Date(),minute));
			}else {
				changePrice.setEffectiveTime(DateUtils.parse(changePriceData.getString("effectiveTime")+" 00:00:00"));
			}
			changePrice.setMenuId(changePriceData.getLong("menuId"));
			changePrice.setOldPrice(item.getDouble("oldPrice"));
			changePrice.setOldVipPrice(item.getDouble("oldVipPrice"));
			changePrice.setOperatorName(operator);
			changePrice.setOperateTime(new Date());
			changePrice.setPrice(item.getDouble("price"));
			changePrice.setReason(changePriceData.getString("reason"));
			changePrice.setSpecId(item.getLong("specId"));
			changePrice.setVipPrice(item.getDouble("vipPrice"));
			changePrice = this.update(changePrice);
			changePriceList.add(changePrice);

			//历史记录
			log = new ChangePriceLog();
			log.setMerchantGroupId(merchantGroupId);
			log.setChangePriceId(changePrice.getId());
			log.setDishesName(dishes.getName());
			log.setEffectiveTime(changePrice.getEffectiveTime());
			log.setOldPrice(changePrice.getOldPrice());
			log.setOldVipPrice(changePrice.getOldVipPrice());
			log.setOperateTime(changePrice.getOperateTime());
			log.setOperatorName(changePrice.getOperatorName());
			log.setPrice(changePrice.getPrice());
			log.setReason(changePrice.getReason());
			log.setSpecName(item.getString("specName"));
			log.setVipPrice(changePrice.getVipPrice());
			changePriceLogService.save(log);

			//删除之前绑定的分店
			changePriceRepository.deletePriceBranch(changePrice.getId());
			Branch branch = null;
			for (int n = 0; n < branchData.size(); n++) {
				//变价分店
				branch = branchService.findById(branchData.getLong(n));
				changePriceBranch = new ChangePriceBranch();
				changePriceBranch.setBranchId(branchData.getLong(n));
				changePriceBranch.setChangePriceId(changePrice.getId());
				changePriceBranch.setDistrictId(branch.getDistrictId());
				changePriceBranch.setMerchantGroupId(merchantGroupId);
				changePriceBranchService.save(changePriceBranch);
			}

		}

		List<Long> bIDs = branchData.toJavaList(Long.class);
		//下发菜品变价
		branchDataReleasedService.updateChangePrices(bIDs,changePriceList);

	}

	@Override
	public void updateData(JSONObject data,String operator) {
		JSONObject changePriceData = data.getJSONObject("changePrice");
		JSONArray branchs = data.getJSONArray("branchs");
		String effectiveTime = data.getString("effectiveTime");
		if(StringUtils.isBlank(effectiveTime)){
			throw new BusinessRunTimeException("请选择生效日期",10001);
		}

		if(CollectionUtils.isEmpty(branchs)){
			throw new BusinessRunTimeException("请选择生效门店",10001);
		}

		Long id = changePriceData.getLong("id");
		ChangePrice changePrice = this.findById(id);
		log.info("branchs:{}",JSON.toJSONString(branchs));


		//生效日期如果是今天 则推迟5分钟
		log.info("0000 --- :{}",DateUtils.today());
		log.info("0000 --- :{}",effectiveTime);
		if (DateUtils.today().equals(effectiveTime)){
			changePrice.setEffectiveTime(DateUtils.offsiteMinute(new Date(),minute));
		}else {
			changePrice.setEffectiveTime(DateUtils.parse(effectiveTime+" 00:00:00"));
		}
		changePrice.setVipPrice(changePriceData.getDouble("vipPrice"));
		changePrice.setPrice(changePriceData.getDouble("price"));
		changePrice.setReason(changePriceData.getString("reason"));
		changePrice.setOperateTime(new Date());
		changePrice.setOperatorName(operator);
		changePrice = this.update(changePrice);
		List<ChangePrice> changePriceList = Lists.newArrayList();
		changePriceList.add(changePrice);
		Searchable searchable = SearchUtils.newSearchableWithMerchantFilter(changePrice.getMerchantGroupId());
		searchable.addSearchParam("changePriceId_eq",changePrice.getId());
		searchable.addSort(Sort.Direction.DESC,"operateTime");
		List<ChangePriceLog> changePriceLogs = changePriceLogService.findWithSort(searchable);
		if(CollectionUtils.isNotEmpty(changePriceLogs)){
			ChangePriceLog log = changePriceLogs.get(0);
			log.setVipPrice(changePrice.getVipPrice());
			log.setOldPrice(changePrice.getOldPrice());
			log.setReason(changePrice.getReason());
			log.setEffectiveTime(changePrice.getEffectiveTime());
			changePriceLogService.update(log);
		}

		//删除之前绑定的分店
		changePriceRepository.deletePriceBranch(changePrice.getId());
		Branch branch = null;
		ChangePriceBranch changePriceBranch=null;
		//变价分店
		for (int i = 0; i < branchs.size(); i++) {
			branch = branchService.findById(branchs.getLong(i));
			changePriceBranch = new ChangePriceBranch();
			changePriceBranch.setBranchId(branchs.getLong(i));
			changePriceBranch.setChangePriceId(changePrice.getId());
			changePriceBranch.setDistrictId(branch.getDistrictId());
			changePriceBranch.setMerchantGroupId(changePrice.getMerchantGroupId());
			changePriceBranchService.save(changePriceBranch);
		}

		//下发变价信息
		List<Long> bIDs = branchs.toJavaList(Long.class);
		branchDataReleasedService.updateChangePrices(bIDs,changePriceList);

	}

	@Override
	public Page<Map<String, Object>> findDataByPage(Searchable searchable,String name, String state, Long districtId, Long merchantGroupId) {
		String sql = "SELECT p.id, p.remark, p.merchant_group_id, p.dishes_id, p.effective_time\n" +
				"\t, p.menu_id, p.old_price, p.old_vip_price, p.operate_time, p.operator_name\n" +
				"\t, p.price, p.reason, p.spec_id, p.state, p.vip_price\n" +
				"\t, d.name AS dishes_name, s.name\n" +
				"FROM change_prices p\n" +
				"\tLEFT JOIN dishess d ON d.id = p.dishes_id\n" +
				"\tLEFT JOIN dishes_specifications s ON s.id = p.spec_id\n" +
				"WHERE p.is_deleted = 0\n" +
				"\tAND p.merchant_group_id = :merchantGroupId ";

		QyMap map = QyMap.map("merchantGroupId",merchantGroupId);
		if(StringUtils.isNotBlank(state)){
			sql += " AND p.state = :state";
			map.setv("state",state);
		}
		if(StringUtils.isNotBlank(name)){
			sql += " AND (d.name LIKE :name OR p.reason LIKE :name)";
			map.setv("name",name);
		}

		if(districtId!=null){
			sql += "and p.id in( SELECT change_price_id from change_price_branchs where district_id = :districtId)";
			map.setv("districtId",districtId);
		}

		Page<Map<String,Object>> mapPage = jdbcTemplate.queryForList(sql,map,searchable.getPage());
		return mapPage;
	}


	/**
	 * 查询变价
	 * @param merchantGroupId
	 * @param menuId
	 * @param dishesId
	 * @param specId
	 * @return
	 */
	private ChangePrice getChangePrice(Long merchantGroupId,Long menuId,Long dishesId,Long specId){
		Searchable searchable = SearchUtils.newSearchableWithMerchantFilter(merchantGroupId);
		searchable.addSearchParam("menuId_eq",menuId);
		searchable.addSearchParam("dishesId_eq",dishesId);
		searchable.addSearchParam("specId_eq",specId);
		ChangePrice changePrice = this.findOne(searchable);
		return changePrice;
	}
}